const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const { type, data } = event
  const wxContext = cloud.getWXContext()
  
  try {
    switch (type) {
      case 'getUser':
        return await db.collection('User')
          .where({ _openid: wxContext.OPENID })
          .get()
      case 'updateUser':
        return await db.collection('User')
          .doc(data._id)
          .update({ data })
      case 'createUser':
        return await db.collection('User')
          .add({ data: { ...data, _openid: wxContext.OPENID } })
      default:
        return { code: 400, msg: '无效操作' }
    }
  } catch (err) {
    return { code: 500, msg: err.message }
  }
}